package cn.wildfire.chat.kit.conversation;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.JsonObject;
import com.kyleduo.switchbutton.SwitchButton;
import com.lqr.imagepicker.ImagePicker;
import com.lqr.imagepicker.bean.ImageItem;
import com.lqr.optionitemview.OptionItemView;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.R2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wildfire.chat.app.extendsion.classes.GroupMembersByApiRequest;
import cn.wildfire.chat.app.extendsion.classes.ResponseEntity;
import cn.wildfire.chat.app.extendsion.https.OkHttpRequest;
import cn.wildfire.chat.app.extendsion.https.ReqCallBack;
import cn.wildfire.chat.app.extendsion.https.ServerUrlClient;
import cn.wildfire.chat.app.extendsion.ui.CustomAppUIDialog;
import cn.wildfire.chat.app.extendsion.ui.TipDialog;
import cn.wildfire.chat.app.extendsion.ui.ToastTip;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;
import cn.wildfire.chat.app.extendsion.widgets.CircleImageView;
import cn.wildfire.chat.app.main.CreateGroupNextDetaileSetActivity;
import cn.wildfire.chat.app.main.MainActivity;
import cn.wildfire.chat.app.main.PersonSilentSetActivity;
import cn.wildfire.chat.kit.ChatManagerHolder;
import cn.wildfire.chat.kit.WfcScheme;
import cn.wildfire.chat.kit.WfcUIKit;
import cn.wildfire.chat.kit.conversationlist.ConversationListViewModel;
import cn.wildfire.chat.kit.conversationlist.ConversationListViewModelFactory;
import cn.wildfire.chat.kit.group.AddGroupMemberActivity;
import cn.wildfire.chat.kit.group.GroupViewModel;
import cn.wildfire.chat.kit.group.RemoveGroupMemberActivity;
import cn.wildfire.chat.kit.group.SetGroupNameActivity;
import cn.wildfire.chat.kit.group.manage.AddGroupManagerActivity;
import cn.wildfire.chat.kit.qrcode.QRCodeActivity;
import cn.wildfire.chat.kit.search.SearchMessageActivity;
import cn.wildfire.chat.kit.third.utils.FileUtils;
import cn.wildfire.chat.kit.third.utils.ImageUtils;
import cn.wildfire.chat.kit.user.UserInfoActivity;
import cn.wildfire.chat.kit.user.UserViewModel;
import cn.wildfire.chat.kit.utils.InputMethodUtils;
import cn.wildfirechat.message.MessageContentMediaType;
import cn.wildfirechat.model.Conversation;
import cn.wildfirechat.model.ConversationInfo;
import cn.wildfirechat.model.GroupInfo;
import cn.wildfirechat.model.GroupMember;
import cn.wildfirechat.model.ModifyGroupInfoType;
import cn.wildfirechat.model.UserInfo;
import cn.wildfirechat.remote.ChatManager;
import cn.wildfirechat.remote.GeneralCallback;
import cn.wildfirechat.remote.GeneralCallback2;
import cn.wildfirechat.remote.UserSettingScope;

public class GroupConversationInfoFragment extends Fragment implements ConversationMemberAdapter.OnMemberClickListener, CompoundButton.OnCheckedChangeListener {

    // group
    @BindView(R2.id.groupLinearLayout_0)
    LinearLayout groupLinearLayout_0;
    @BindView(R2.id.groupNameOptionItemView)
    OptionItemView groupNameOptionItemView;
    @BindView(R2.id.groupQRCodeOptionItemView)
    TextView groupQRCodeOptionItemView;
    @BindView(R2.id.groupNoticeLinearLayout)
    LinearLayout noticeLinearLayout;
    @BindView(R2.id.groupNoticeTextView)
    TextView noticeTextView;
    @BindView(R2.id.groupManageOptionItemView)
    TextView groupManageOptionItemView;
    @BindView(R2.id.groupManageDividerLine)
    View groupManageDividerLine;

    @BindView(R2.id.myGroupNickNameOptionItemView)
    TextView myGroupNickNameOptionItemView;
    @BindView(R2.id.groupNickNameTextView)
    TextView groupNickNameTextView;
    @BindView(R2.id.showGroupMemberAliasSwitchButton)
    SwitchButton showGroupMemberNickNameSwitchButton;

    @BindView(R2.id.quitButton)
    Button quitGroupButton;

    @BindView(R2.id.markGroupLinearLayout)
    LinearLayout markGroupLinearLayout;
    @BindView(R2.id.markGroupSwitchButton)
    SwitchButton markGroupSwitchButton;

    // common
    @BindView(R2.id.memberRecyclerView)
    RecyclerView memberReclerView;
    @BindView(R2.id.stickTopSwitchButton)
    SwitchButton stickTopSwitchButton;
    @BindView(R2.id.silentSwitchButton)
    SwitchButton silentSwitchButton;
    @BindView(R2.id.totalSilenceLayout)
    LinearLayout totalSilenceLayout;
    @BindView(R2.id.portraitManageOptionItemView)
    OptionItemView portraitManageOptionItemView;


    @BindView(R2.id.groupPortraitImg)
    CircleImageView groupPortraitImg;
    @BindView(R2.id.groupNameTextView)
    TextView groupNameTextView;
    @BindView(R2.id.groupNumberTextView)
    TextView groupNumberTextView;
    @BindView(R2.id.searchMessageOptionItemView)
    TextView searchMessageOptionItemView;
    @BindView(R2.id.lookGroupPersonsInfoOptionItemView)
    TextView lookGroupPersonsInfoOptionItemView;
    @BindView(R2.id.tousuOptionItemView)
    TextView tousuOptionItemView;
    @BindView(R2.id.tousuLineView)
    View tousuLineView;
    @BindView(R2.id.clearMessagesOptionItemView)
    TextView clearMessagesOptionItemView;
    @BindView(R2.id.totalSlienceSwitchButton)
    SwitchButton totalSlienceSwitchButton;
    @BindView(R2.id.personSilentOptionItemView)
    TextView personSilentOptionItemView;
    @BindView(R2.id.portraitManageDividerLine)
    View portraitManageDividerLine;
    @BindView(R2.id.changeGroupInfoLayout)
    LinearLayout changeGroupInfoLayout;

    private ConversationInfo conversationInfo;
    private ConversationMemberAdapter conversationMemberAdapter;
    private ConversationViewModel conversationViewModel;
    private UserViewModel userViewModel;

    private GroupViewModel groupViewModel;
    private GroupInfo groupInfo;
    // me in group
    private GroupMember groupMember;


    public static GroupConversationInfoFragment newInstance(ConversationInfo conversationInfo) {
        GroupConversationInfoFragment fragment = new GroupConversationInfoFragment();
        Bundle args = new Bundle();
        args.putParcelable("conversationInfo", conversationInfo);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        assert args != null;
        conversationInfo = args.getParcelable("conversationInfo");
        assert conversationInfo != null;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.conversation_info_group_fragment, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        isFromModifySelfGroupNickName = false;
        conversationViewModel = ViewModelProviders.of(this, new ConversationViewModelFactory(conversationInfo.conversation)).
                get(ConversationViewModel.class);
        userViewModel = WfcUIKit.getAppScopeViewModel(UserViewModel.class);
        groupLinearLayout_0.setVisibility(View.VISIBLE);
        markGroupLinearLayout.setVisibility(View.GONE);

        totalSlienceSwitchButton.setOnCheckedChangeListener(this);

        quitGroupButton.setVisibility(View.VISIBLE);

        groupViewModel = ViewModelProviders.of(this).get(GroupViewModel.class);

        loadAndShowGroupMembers(true);
        if (groupMember == null || groupInfo == null) {
            return;
        }
        refreshUI();
        observerFavGroupsUpdate();
        observerGroupInfoUpdate();
        observerGroupMembersUpdate();
        setGroupBaseInfo();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    /**
     * 设置基础信息
     */
    @SuppressLint("SetTextI18n")
    private void setGroupBaseInfo() {
        try {
            totalSlienceSwitchButton.setCheckedNoEvent(groupInfo.mute == 1);
            String name = groupInfo.name;
            if (!TextUtils.isTextEmpty(name) && name.length() >= 15) {
                name = name.substring(0, 14) + "等";
            }
            groupNameTextView.setText("" + name);
            Glide.with(getContext()).load(groupInfo.portrait).apply(new RequestOptions().placeholder(R.mipmap.button_group).centerCrop())
                    .into(groupPortraitImg);
            if (groupMember != null && (groupMember.type == GroupMember.GroupMemberType.Owner ||
                    groupMember.type == GroupMember.GroupMemberType.Manager)) {
                changeGroupInfoLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(getActivity(), CreateGroupNextDetaileSetActivity.class);
                        intent.putExtra("choosetype", CreateGroupNextDetaileSetActivity.TYPE_MODIFY_GROUP);
                        intent.putExtra("groupInfo", groupInfo);
                        getActivity().startActivity(intent);
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * modify by HEKE , 2019/8/27 12:25
     * TODO 刷新显示
     */
    private void refreshUI() {
        try {
            showGroupMemberNickNameSwitchButton.setChecked("1".equals(userViewModel.getUserSetting(UserSettingScope.GroupHideNickname, groupInfo.target)));
            showGroupMemberNickNameSwitchButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
                userViewModel.setUserSetting(UserSettingScope.GroupHideNickname, groupInfo.target, isChecked ? "1" : "0");
            });
            groupNameOptionItemView.setRightText(groupInfo.name);
            stickTopSwitchButton.setChecked(conversationInfo.isTop);
            silentSwitchButton.setChecked(conversationInfo.isSilent);
            stickTopSwitchButton.setOnCheckedChangeListener(this);
            silentSwitchButton.setOnCheckedChangeListener(this);
            boolean onwer = groupInfo != null && ChatManagerHolder.gChatManager.getUserId().equals(groupInfo.owner);
            if (onwer) {
                quitGroupButton.setText(R.string.delete_and_dismiss);
            } else {
                quitGroupButton.setText(R.string.delete_and_exit);
            }
            /**
             * modify by HEKE , 2019/9/9 18:39 TODO 显示内容处理
             */
            // 群主
            if (groupMember.type == GroupMember.GroupMemberType.Owner) {
                tousuOptionItemView.setVisibility(View.GONE);
                tousuLineView.setVisibility(View.GONE);
                groupManageOptionItemView.setVisibility(View.VISIBLE);
                totalSilenceLayout.setVisibility(View.VISIBLE);
                personSilentOptionItemView.setVisibility(View.VISIBLE);
            }
            // 管理员
            else if (groupMember.type == GroupMember.GroupMemberType.Manager) {
                tousuOptionItemView.setVisibility(View.VISIBLE);
                tousuLineView.setVisibility(View.VISIBLE);
                totalSilenceLayout.setVisibility(View.VISIBLE);
                groupManageOptionItemView.setVisibility(View.GONE);
                personSilentOptionItemView.setVisibility(View.GONE);
            }
            // 普通成员
            else {
                tousuOptionItemView.setVisibility(View.VISIBLE);
                tousuLineView.setVisibility(View.VISIBLE);
                totalSilenceLayout.setVisibility(View.GONE);
                groupManageOptionItemView.setVisibility(View.GONE);
                personSilentOptionItemView.setVisibility(View.GONE);
            }
            // 非来自于手动修改设置时修改显示内容
            if (!isFromModifySelfGroupNickName) {
                String selfAlias = groupMember.alias;
                groupNickNameTextView.setText(selfAlias);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void observerFavGroupsUpdate() {
        groupViewModel.getMyGroups().observe(this, listOperateResult -> {
            if (listOperateResult.isSuccess()) {
                for (GroupInfo info : listOperateResult.getResult()) {
                    if (groupInfo.target.equals(info.target)) {
                        markGroupSwitchButton.setChecked(true);
                        break;
                    }
                }
            }
        });
    }

    private void observerGroupMembersUpdate() {
        groupViewModel.groupMembersUpdateLiveData().observe(this, groupMembers -> {
            loadAndShowGroupMembers(true);
        });
    }

    private void observerGroupInfoUpdate() {
        groupViewModel.groupInfoUpdateLiveData().observe(this, groupInfos -> {
            for (GroupInfo groupInfo : groupInfos) {
                if (groupInfo.target.equals(this.groupInfo.target)) {
                    groupNameOptionItemView.setRightText(groupInfo.name);
                    loadAndShowGroupMembers(true);
                    break;
                }
            }
        });
    }

    /**
     * 强制刷新数据
     */
    public void forceRefresh() {
        init();
    }

    /**
     * modify by HEKE , 2019/8/24 12:07
     * TODO 重置用户数据调整
     *
     * @param refresh
     */
    private void loadAndShowGroupMembers(boolean refresh) {
        try {
            groupInfo = groupViewModel.getGroupInfo(conversationInfo.conversation.target, true);
            List<GroupMember> groupMembers = groupViewModel.getGroupMembers(groupInfo.target, true);
            /**
             *  Create by HEKE, 2019/8/25 22:19
             *  TODO 修改重点
             */
            setGroupBaseInfo();
            String userId = userViewModel.getUserId();
            loadDatas(userId, groupMembers);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载继续操作
     *
     * @param userId
     * @param groupMembers
     */
    private void loadDatas(String userId, List<GroupMember> groupMembers) {
        try {
            GroupMember owerMember = null;
            List<String> memberIds = new ArrayList<>();
            for (GroupMember member : groupMembers) {
                if (member.memberId.equals(userId)) {
                    groupMember = member;
                }
                if (member.type != GroupMember.GroupMemberType.Removed) {
                    memberIds.add(member.memberId);
                }
                if (groupInfo.owner.equals(member.memberId)) {
                    owerMember = member;
                }
            }
            if (groupMember == null || groupInfo == null) {
                Toast.makeText(getActivity(), "你不在群组或发生错误, 请稍后再试", Toast.LENGTH_SHORT).show();
                getActivity().finish();
                return;
            }

            /**
             * modify by HEKE , 2019/8/24 12:11
             * TODO 对比自身与群组之间的数据变化
             */
            if (groupInfo.owner.equals(groupMember.memberId)) {
                groupMember.type = GroupMember.GroupMemberType.Owner;
            } else if (groupMember.type == GroupMember.GroupMemberType.Manager) {
            } else {
                groupMember.type = GroupMember.GroupMemberType.Normal;
            }

            refreshUI();

            boolean enableRemoveMember = false;
            boolean enableAddMember = false;
            if (groupInfo.joinType == 2) {
                if (groupMember.type == GroupMember.GroupMemberType.Owner || groupMember.type == GroupMember.GroupMemberType.Manager) {
                    enableAddMember = true;
                    enableRemoveMember = true;
                }
            } else {
                enableAddMember = true;
                if (groupMember.type != GroupMember.GroupMemberType.Normal || userId.equals(groupInfo.owner)) {
                    enableRemoveMember = true;
                }
            }
            conversationMemberAdapter = new ConversationMemberAdapter(enableAddMember, enableRemoveMember);
            List<UserInfo> members = ChatManager.Instance().getUserInfos(memberIds, groupInfo.target);
            try {
                /**
                 * modify by HEKE , 2019/8/27 12:17
                 * TODO 解决getUserInfos 通道返回用户级别信息错误问题
                 */
                for (UserInfo userInfo : members) {
                    for (GroupMember groupMember : groupMembers) {
                        if (userInfo.uid.equals(groupMember.memberId)) {
                            userInfo.type = groupMember.type.value();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            List<UserInfo> sortList = new ArrayList<>();
            try {
                if (owerMember != null) {
                    for (UserInfo member : members) {
                        if (owerMember.memberId.equals(member.uid)) {
                            sortList.add(member);
                        }
                    }
                    for (UserInfo member : members) {
                        if (!owerMember.memberId.equals(member.uid)) {
                            sortList.add(member);
                        }
                    }
                } else {
                    sortList = members;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            conversationMemberAdapter.setMembers(sortList);
            conversationMemberAdapter.setOnMemberClickListener(this);
            memberReclerView.setAdapter(conversationMemberAdapter);
            memberReclerView.setLayoutManager(new GridLayoutManager(getActivity(), 5));
            memberReclerView.setNestedScrollingEnabled(false);
            memberReclerView.setHasFixedSize(true);
            memberReclerView.setFocusable(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick(R2.id.groupNameOptionItemView)
    void updateGroupName() {
        if (groupInfo.type != GroupInfo.GroupType.Restricted
                || (groupMember.type == GroupMember.GroupMemberType.Manager || groupMember.type == GroupMember.GroupMemberType.Owner)) {
            Intent intent = new Intent(getActivity(), SetGroupNameActivity.class);
            intent.putExtra("groupInfo", groupInfo);
            startActivity(intent);
        }
    }

    @OnClick(R2.id.groupNoticeLinearLayout)
    void updateGroupNotice() {
        // TODO
    }

    /**
     * 当前管理员成员
     */
    protected List<GroupMember> managerMembers = new ArrayList<>();
    protected boolean canRequestManagerGroup;

    @OnClick(R2.id.groupManageOptionItemView)
    void manageGroup() {
        if (!canRequestManagerGroup) {
            canRequestManagerGroup = true;
            new GroupMembersByApiRequest(getContext(), groupInfo.target, new GroupMembersByApiRequest.OnGetGroupMembersListener() {
                @Override
                public void result(List<GroupMember> groupMemberList) {
                    canRequestManagerGroup = false;
                    managerMembers.clear();
                    GroupMember ownerMember = null;
                    ArrayList<String> totalMemberIds = new ArrayList<>();
                    for (GroupMember member : groupMemberList) {
                        if (member.type != GroupMember.GroupMemberType.Owner) {
                            totalMemberIds.add(member.memberId);
                        } else {
                            ownerMember = member;
                        }
                        if (member.type == GroupMember.GroupMemberType.Manager) {
                            managerMembers.add(member);
                        }
                    }
                    // 跳转至选择界面
                    Intent intent = new Intent(getActivity(), AddGroupManagerActivity.class);
                    intent.putExtra("groupInfo", groupInfo);
                    ArrayList<String> memberIds = new ArrayList<>(managerMembers.size());
                    for (GroupMember member : managerMembers) {
                        memberIds.add(member.memberId);
                    }
                    intent.putStringArrayListExtra("initCheckedMemberIds", memberIds);
                    intent.putExtra("ownerId", "" + ownerMember.memberId);
                    startActivity(intent);
                }
            });
        }
    }

    // 来自于群组设置刷新显示群昵称标记
    protected boolean isFromModifySelfGroupNickName;

    @OnClick(R2.id.myGroupNickNameOptionItemView)
    void updateMyGroupAlias() {
        MaterialDialog dialog = new MaterialDialog.Builder(getActivity())
                .input("请输入你的群昵称", groupMember.alias, true, (dialog1, input) -> {
                    String modifyName = input.toString();
                    if (TextUtils.isTextEmpty(modifyName)) {
                        modifyName = "";
                    }
                    final String finalModifyName = modifyName;
                    groupViewModel.modifyMyGroupAlias(groupInfo.target, modifyName)
                            .observe(GroupConversationInfoFragment.this, operateResult -> {
                                if (operateResult.isSuccess()) {
                                    isFromModifySelfGroupNickName = true;
                                    String setModifyName = finalModifyName;
                                    groupNickNameTextView.setText(setModifyName);
                                } else {
                                    Toast.makeText(getActivity(), "修改群昵称失败:" + operateResult.getErrorCode(), Toast.LENGTH_SHORT).show();
                                }
                            });
                }).inputRange(0, 16)
                .title(getString(R.string.set_group_nickname))
                .negativeText("取消")
                .positiveText("确定")
                .onPositive((dialog12, which) -> {
                    dialog12.dismiss();
                })
                .build();
        dialog.show();
    }

    @OnClick(R2.id.quitButton)
    void quitGroup() {
        boolean onwer = (groupInfo != null && userViewModel.getUserId().equals(groupInfo.owner));
        if (onwer) {
            TipDialog.showCustomDialog(getActivity(), getString(R.string.dissovle_group_title), getString(R.string.dissovle_group_tip)
                    , new String[]{getString(R.string.confirm), getString(R.string.cancle_but)}, CustomAppUIDialog.TYPE_CONFIRM_CANCLE, true
                    , 2, true, new TipDialog.OnMsgTipDialogListener() {
                        @Override
                        public void then(boolean confirm, boolean outtouch) {
                            if (confirm) {
                                groupViewModel.dismissGroup(conversationInfo.conversation.target, Collections.singletonList(0)).
                                        observe(GroupConversationInfoFragment.this, aBoolean -> {
                                            if (aBoolean != null && aBoolean) {
                                                Intent intent = new Intent(getActivity(), MainActivity.class);
                                                startActivity(intent);
                                            } else {
                                                ToastTip.tip(getString(R.string.dissovle_group_failure));
                                            }
                                        });
                            }
                        }
                    });
        } else {
            TipDialog.showCustomDialog(getActivity(), getString(R.string.quit_group_title), getString(R.string.quit_group_tip)
                    , new String[]{getString(R.string.confirm), getString(R.string.cancle_but)}, CustomAppUIDialog.TYPE_CONFIRM_CANCLE, true
                    , 2, true, new TipDialog.OnMsgTipDialogListener() {
                        @Override
                        public void then(boolean confirm,boolean outtouch) {
                            if (confirm) {
                                groupViewModel.quitGroup(conversationInfo.conversation.target, Collections.singletonList(0))
                                        .observe(GroupConversationInfoFragment.this, aBoolean -> {
                                            if (aBoolean != null && aBoolean) {
                                                Intent intent = new Intent(getActivity(), MainActivity.class);
                                                startActivity(intent);
                                            } else {
                                                ToastTip.tip(getString(R.string.quit_group_failure));
                                            }
                                        });
                            }
                        }
                    });
        }
    }

    @OnClick(R2.id.clearMessagesOptionItemView)
    void clearMessage() {
        TipDialog.showCustomDialog(getActivity(), getString(R.string.wendy_title), getString(R.string.delete_msgs_tip)
                , new String[]{getString(R.string.confirm), getString(R.string.cancle_but)}, CustomAppUIDialog.TYPE_CONFIRM_CANCLE, true
                , 2, true, new TipDialog.OnMsgTipDialogListener() {
                    @Override
                    public void then(boolean confirm,boolean outtouch) {
                        if (confirm) {
                            conversationViewModel.clearConversationMessage(conversationInfo.conversation);
                        }
                    }
                });
    }

    @OnClick(R2.id.groupQRCodeOptionItemView)
    void showGroupQRCode() {
        String qrCodeValue = WfcScheme.QR_CODE_PREFIX_GROUP + groupInfo.target;
        Intent intent = QRCodeActivity.buildQRCodeIntent(getActivity(), getString(R.string.group_qrcode), groupInfo.portrait, qrCodeValue, groupInfo);
        startActivity(intent);
    }

    @OnClick(R2.id.searchMessageOptionItemView)
    void searchGroupMessage() {
        Intent intent = new Intent(getActivity(), SearchMessageActivity.class);
        intent.putExtra("conversation", conversationInfo.conversation);
        startActivity(intent);
    }

    @Override
    public void onUserMemberClick(UserInfo userInfo) {
        try {
            /**
             * modify by HEKE , 2019/8/23 18:21
             * TODO 拒绝交友修改传输数据
             */
            if (groupInfo != null) {
                Intent intent = new Intent(getActivity(), UserInfoActivity.class);
                intent.putExtra("userInfo", userInfo);
                intent.putExtra("privateChat", groupInfo.privateChat);
                intent.putExtra("normal", (groupMember.type == GroupMember.GroupMemberType.Normal) ? "1" : "0");
                intent.putExtra("groupInfo", groupInfo);
                startActivity(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onAddMemberClick() {
        Intent intent = new Intent(getActivity(), AddGroupMemberActivity.class);
        intent.putExtra("groupInfo", groupInfo);
        startActivity(intent);
    }

    @Override
    public void onRemoveMemberClick() {
        if (groupInfo != null) {
            Intent intent = new Intent(getActivity(), RemoveGroupMemberActivity.class);
            intent.putExtra("groupInfo", groupInfo);
            startActivity(intent);
        }
    }

    private void stickTop(boolean top) {
        ConversationListViewModel conversationListViewModel = ViewModelProviders
                .of(this, new ConversationListViewModelFactory(Arrays.asList(Conversation.ConversationType.Single, Conversation.ConversationType.Group, Conversation.ConversationType.Channel), Arrays.asList(0)))
                .get(ConversationListViewModel.class);
        conversationListViewModel.setConversationTop(conversationInfo, top);
    }

    private void markGroup(boolean mark) {
        groupViewModel.setFavGroup(groupInfo.target, mark);
    }

    private void silent(boolean silent) {
        conversationViewModel.setConversationSilent(conversationInfo.conversation, silent);
    }

    private void mute(boolean mute) {
        groupViewModel.muteAll(groupInfo.target, mute).observe(this, booleanOperateResult -> {
            if (!booleanOperateResult.isSuccess()) {
                totalSlienceSwitchButton.setCheckedNoEvent(!mute);
                ToastTip.tip("禁言失败 " + booleanOperateResult.getErrorCode());
            }
        });
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        int id = buttonView.getId();
        if (id == R.id.markGroupSwitchButton) {// 已过时
            markGroup(isChecked);
        } else if (id == R.id.stickTopSwitchButton) {// 置顶显示
            stickTop(isChecked);
        } else if (id == R.id.silentSwitchButton) {// 免打扰
            silent(isChecked);
        } else if (id == R.id.totalSlienceSwitchButton) {// 全员禁言
            mute(isChecked);
        }
    }

    /**
     * modify by HEKE , 2019/10/8 18:04 TODO 个人禁言
     */
    @OnClick(R2.id.personSilentOptionItemView)
    public void personSilent() {
        try {
            Intent intent = new Intent(getContext(), PersonSilentSetActivity.class);
            intent.putExtra("groupInfo", groupInfo);
            intent.putExtra("isNotGroupChoose", true);
            getContext().startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static final int REQUEST_CODE_PICK_IMAGE = 1000;

    @OnClick(R2.id.portraitManageOptionItemView)
    public void portraitSet() {
        /**
         * modify by HEKE , 2019/8/24 4:52
         * TODO 群头像设置
         */
        try {
            ImagePicker.picker().pick(this, REQUEST_CODE_PICK_IMAGE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
            ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            String imagePath = ImageUtils.genThumbImgFile(images.get(0).path).getAbsolutePath();
            ChatManager.Instance().getWorkHandler().post(() -> {
                String groupPortrait = imagePath;
                if (groupPortrait != null) {
                    byte[] content = FileUtils.readFile(groupPortrait);
                    ChatManager.Instance().uploadMedia(content, MessageContentMediaType.PORTRAIT.getValue(), new GeneralCallback2() {
                        @Override
                        public void onSuccess(String result) {
                            ChatManager.Instance().modifyGroupInfo(groupInfo.target, ModifyGroupInfoType.Modify_Group_Portrait,
                                    result, Collections.singletonList(0), null, new GeneralCallback() {
                                        @Override
                                        public void onSuccess() {
                                            Toast.makeText(getContext(), "更换头像成功!", Toast.LENGTH_SHORT).show();
                                        }

                                        @Override
                                        public void onFail(int errorCode) {
                                            Toast.makeText(getContext(), "更换头像失败!", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                        }

                        @Override
                        public void onFail(int errorCode) {
                            Toast.makeText(getContext(), "更换头像失败!", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @OnClick({R2.id.lookGroupPersonsInfoOptionItemView, R2.id.tousuOptionItemView})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.lookGroupPersonsInfoOptionItemView) {// 查看群成员
            Intent intent = new Intent(getActivity(), ViewGroupMemberActivity.class);
            intent.putExtra("GroupID", groupInfo.target);
            startActivity(intent);
        } else if (id == R.id.tousuOptionItemView) {// 投诉
            ShowReportPopWindow();
        }
    }


    PopupWindow popupWindow;

    private void ShowReportPopWindow() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.pop_report, null);
        popupWindow = new PopupWindow(view, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);

        Button cancel = view.findViewById(R.id.btn_cancel);
        Button confirm = view.findViewById(R.id.btn_confirm);
        EditText etReport = view.findViewById(R.id.et_report);
        etReport.setFocusable(true);
        etReport.setFocusableInTouchMode(true);
        etReport.requestFocus();
        InputMethodUtils.showOrHide(getActivity());
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });


        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String reportText = etReport.getText().toString().trim();
                if (TextUtils.isTextEmpty(reportText)) {
                    ToastTip.tip(getString(R.string.message_can_not_null));
                    return;
                }

                HashMap<String, Object> params = new HashMap<>();
                params.put("from", userViewModel.getUserId());
                params.put("message", reportText);
                params.put("target", groupInfo.target);
                params.put("type", "2");
                OkHttpRequest.getNewInstance(getActivity()).requestAsynJsonObject(ServerUrlClient.REQUEST_REPORT_FRIEND, params, new ReqCallBack<Object>() {
                    @Override
                    public void onReqSuccess(Object result) {
                        try {
                            String ret = result.toString();
                            if (ret != null) {
                                ResponseEntity<JsonObject, String> responseEntity = new ResponseEntity(result.toString());
                                if (responseEntity.isSuccess()) {
                                    Toast.makeText(getActivity(), "投诉成功,我们将在24小时内处理.", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(getActivity(), "举报失败", Toast.LENGTH_SHORT).show();
                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {

                    }
                }).request();
                popupWindow.dismiss();
            }
        });


        setAlph(0.9f);
        popupWindow.showAtLocation(tousuOptionItemView, Gravity.CENTER, 0, 0);

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setAlph(1f);
            }
        });

    }

    private void setAlph(float f) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        //0.0-1.0
        lp.alpha = f;
        getActivity().getWindow().setAttributes(lp);
    }

}
